<template>
	<view class="page">
		<view class="notice">
			<text>我们需要获取您的摄像头权限，在司机报名阶段用于身份证、驾驶证拍照上传，以便平台进行身份验证</text>
		</view>
		<view class="credentials-container">
			<view class="credentials">
				<image :src="idcardPhoto[0]" class="bg"></image>
				<view class="cover">
					<image src="../../static/auth/card.png" mode="widthFix" class="card"></image>
					<text class="desc">身份证正面</text>
					<ocr-navigator @onSuccess="takeIdCardFrontPhoto" certificateType="idCard" :opposite="false">
						<button class="camera"></button>
					</ocr-navigator>
				</view>
			</view>
			<view class="credentials">
				<image :src="idcardPhoto[1]" class="bg"></image>
				<view class="cover">
					<image src="../../static/auth/card.png" mode="widthFix" class="card"></image>
					<text class="desc">身份证背面</text>
					<ocr-navigator @onSuccess="takeIdCardBackPhoto" certificateType="idCard" :opposite="true"><button
							class="camera"></button></ocr-navigator>
				</view>
			</view>
			<view class="credentials">
				<image :src="idcardPhoto[2]" class="bg"></image>
				<view class="cover">
					<image src="../../static/auth/card.png" mode="widthFix" class="card"></image>
					<text class="desc">手持身份证</text>
					<button class="camera" @tap="handPhoto('idcardHolding')"></button>
				</view>
			</view>
			<view class="credentials">
				<image :src="idcardPhoto[3]" class="bg"></image>
				<view class="cover">
					<image src="../../static/auth/card.png" mode="widthFix" class="card"></image>
					<text class="desc">驾驶证正面</text>
					<ocr-navigator @onSuccess="takeDriverCardFront" certificateType="driverslicense"><button
							class="camera"></button></ocr-navigator>
				</view>
			</view>
			<view class="credentials">
				<image :src="idcardPhoto[4]" class="bg"></image>
				<view class="cover">
					<image src="../../static/auth/card.png" mode="widthFix" class="card"></image>
					<text class="desc">驾驶证背面</text>
					<button class="camera" @tap="handPhoto('drcardBack')"></button>
				</view>
			</view>
			<view class="credentials">
				<image :src="idcardPhoto[5]" class="bg"></image>
				<view class="cover">
					<image src="../../static/auth/card.png" mode="widthFix" class="card"></image>
					<text class="desc">手持驾驶证</text>
					<button class="camera" @tap="handPhoto('drcardHolding')"></button>
				</view>
			</view>
		</view>


		<view class="text_nav"><text>个人信息</text></view>
		<view class="list">
			<u-cell-group border="false">
				<u-cell title="真实姓名" :value="idcard.name" :value-style="style" :arrow="false" />
				<u-cell title="性别" :value="idcard.gender" :value-style="style" :arrow="false" />
				<u-cell title="生日" :value="idcard.birthday" :value-style="style" :arrow="false" />
				<u-cell title="身份证号" :value="idcard.pid" :value-style="style" :arrow="false" />
				<u-cell title="身份证地址" :value="idcard.shortAddress" :value-style="style" @click="showAddressContent" />
				<u-cell title="身份证有效期" :value="idcard.expiration" :value-style="style" :arrow="false" />
			</u-cell-group>
		</view>
		<view class="text_nav"><text>联系方式</text></view>
		<view class="list">
			<u-cell-group border="false">
				<u-cell title="手机号码" :value="contact.tel" :value-style="style" @click="inputData('手机号码', 'tel')" />
				<u-cell title="电子信箱" :value="contact.shortEmail" :value-style="style"
					@click="inputData('电子信箱', 'email')" />
				<u-cell title="收信地址" :value="contact.shortMailAddress" :value-style="style"
					@click="inputData('收信地址', 'mailAddress')" />
				<u-cell title="紧急联系人" :value="contact.contactName" :value-style="style"
					@click="inputData('紧急联系人', 'contactName')" />
				<u-cell title="紧急联系人电话" :value="contact.contactTel" :value-style="style"
					@click="inputData('紧急联系人电话', 'contactTel')" />
			</u-cell-group>
		</view>
		<view class="text_nav"><text>驾驶证</text></view>
		<view class="list">
			<u-cell-group border="false">
				<u-cell title="驾驶证类型" :value="drcard.carClass" :value-style="style" :arrow="false" />
				<u-cell title="驾驶证有效期" :value="drcard.validTo" :value-style="style" :arrow="false" />
				<u-cell title="初次领证日期" :value="drcard.issueDate" :value-style="style" :arrow="false" />
			</u-cell-group>
		</view>

		<button class="btn" @click="save" :disabled="realAuth == 3">提交审核</button>
		<view class="remark">感谢您的提交实名，我们在接下来1-3个工作日审核你的信息，这期间您将无法接单，请耐心等候！</view>
		<u-toast ref="uToast" />
	</view>
	</view>
</template>

<script>
	import dayjs from 'dayjs';
	export default {
		data() {
			return {
				idcardPhoto: [
					'../../static/auth/credentials-bg.jpg', //身份证正面  OCR
					'../../static/auth/credentials-bg.jpg', //身份证背面  OCR
					'../../static/auth/credentials-bg.jpg', //手持身份证照片  camera 
					'../../static/auth/credentials-bg.jpg', //驾驶证正面  OCR
					'../../static/auth/credentials-bg.jpg', //驾驶证背面照片  camera 
					'../../static/auth/credentials-bg.jpg' // 手持驾驶证  camera
				],
				idcard: {
					pid: '', //身份证
					name: '', //姓名
					gender: '', //性别
					address: '', //地址
					shortAddress: '', //缩写地址
					birthday: '', //生日
					expiration: '', //身份证过期日期
					idcardFront: '', //身份证正面照片
					idcardBack: '', // 身份证背面照片
					idcardHolding: '' //手持身份证照片
				},
				contact: {
					tel: '',
					email: '',
					shortEmail: '',
					mailAddress: '',
					shortMailAddress: '',
					contactName: '',
					contactTel: ''
				},
				drcard: {
					issueDate: '', //发证日期
					carClass: '', //准驾车型
					validFrom: '', //证件有效日期开始日期
					validTo: '', //证件有效日期截止日期
					drcardFront: '', //驾驶证正面照
					drcardBack: '', //驾驶证背面照
					drcardHolding: '' ////驾驶证手持照
				},
				currentImg: {},
				realAuth: uni.getStorageSync('realAuth')
			}
		},
		methods: {

			takeIdCardFrontPhoto(resp) {
				console.log('身份证正面照片', resp);
				let that = this;
				let detail = resp.detail;
				that.idcard.pid = detail.id.text;
				that.idcard.name = detail.name.text;
				that.idcard.gender = detail.gender.text;
				that.idcard.address = detail.address.text;
				//文字太长缩略身份证地址
				that.idcard.shortAddress = detail.address.text.substr(0, 15) + '...';
				that.idcard.birthday = detail.birth.text;
				//OCR插件拍摄到的身份证正面照片存储地址
				that.idcard.idcardFront = detail.image_path;
				that.idcardPhoto[0] = detail.image_path;
				that.uploadCos(that.urls.uploadPrivate, detail.image_path, function(resp) {
					let path = resp.path;
					that.currentImg['idcardFront'] = path;
				});
			},
			takeIdCardBackPhoto: function(resp) {
				console.log('身份证背面照片', resp);
				let detail = resp.detail;
				let that = this;
				//OCR插件拍摄到的身份证背面照片存储地址
				this.idcard.idcardBack = detail.image_path;
				//View标签加载身份证背面照片
				this.idcardPhoto[1] = detail.image_path;
				let validDate = detail.valid_date.text.split('-')[1];
				this.idcard.expiration = dayjs(validDate, 'YYYYMMDD').format('YYYY-MM-DD');
				this.uploadCos(this.urls.uploadPrivate, detail.image_path, function(resp) {
					let path = resp.path;
					console.log('uploadCos idback path ', path);
					that.currentImg['idcardBack'] = path;
				});
			},
			handPhoto: function(type) {
				uni.navigateTo({
					url: '../camera/camera?type=' + type // 类型： 手持驾驶证 手持身份证  驾驶证背面拍照
				});
			},
			takeDriverCardFront: function(resp) {
				let that = this;
				let detail = resp.detail;
				console.log('驾驶证正面照片', resp);
				that.drcard.issueDate = detail.issue_date.text; //初次领证日期
				that.drcard.carClass = detail.car_class.text; //准驾车型
				that.drcard.validFrom = detail.valid_from.text; //驾驶证起始有效期
				that.drcard.validTo = detail.valid_to.text; //驾驶证截止有效期
				that.drcard.drcardFront = detail.image_path;
				that.idcardPhoto[3] = detail.image_path;
				that.uploadCos(that.urls.uploadPrivate, detail.image_path, function(data) {
					let path = data.path;
					that.currentImg['drcardFront'] = path;
				});
			},
			inputData: function(title, key) {
				let that = this;
				uni.showModal({
					title: title,
					editable: true,
					content: that.contact[key],
					success: function(resp) {
						if (resp.confirm) {
							if (key == 'mailAddress') {
								that.contact['shortMailAddress'] = resp.content.substr(0, 15) + (resp
									.content.length > 15 ? '...' : '');
							} else if (key == 'email') {
								that.contact['shortEmail'] = resp.content.substr(0, 25) + (resp.content
									.length > 25 ? '...' : '');
							}
							that.contact[key] = resp.content;
						}
					}
				});
			},
			updatePhoto: async function(type, path) {
				let that = this;
				try {
					// 等待uploadCos操作完成
					let data = await new Promise((resolve, reject) => {
						that.uploadCos(that.urls.uploadPrivate, path, function(response) {
							if (response.error) {
								reject(response.error); // 处理错误情况
							} else {
								resolve(response); // 处理成功情况
							}
						});
					});

					console.log("updatePhoto result", data);
					if (type == 'idcardHolding') {
						// 对于数组更新
						this.$set(this.idcardPhoto, 2, path);
						// 对于对象更新
						this.$set(this.currentImg, 'idcardHolding', data.path);
						this.idcard.idcardHolding = data.path;
					} else if (type == 'drcardBack') {
						this.$set(this.idcardPhoto, 4, path);
						this.$set(this.currentImg, 'drcardBack', data.path);
						this.idcard.drcardBack = data.path;
					} else if (type == 'drcardHolding') {
						this.$set(this.idcardPhoto, 5, path);
						this.$set(this.currentImg, 'drcardHolding', data.path);
						this.idcard.drcardHolding = data.path;
					}

				} catch (error) {
					console.error("updatePhoto error", error);
					// 处理上传过程中的错误
				}
			},
			async save() {
				// 1.校验司机身份照片是否都完成提交
				// 2.校验司机联系信息是否正确
				// const {
				// 	currentImg,
				// 	contact,
				// 	idcard,
				// 	drcard
				// } = this;
				// const checkImg = await this.checkUploadImages(currentImg);
				// if (!checkImg) return;

				// const checkValidContactInfo = await this.checkValidContactInfo(contact);
				// if (!checkValidContactInfo) return;

				// // 3.交互确认是否要提交资料 
				// const confirmSubmission = await this.confirmSubmission();
				// if (!confirmSubmission) return;

				// // 4.组装数据
				// const data = await this.createFormData(idcard, contact, currentImg, drcard);
				// console.log('组装司机实名信息', data);

				// // 5.更新司机实名信息
				// const result = await this.callAsync(this.urls.updateDriverAuth, 'POST', data);
				// console.log('司机实名认证 response', result);

				// todo 6. 进入人脸识别 活体检测页面
				await this.showSuccessMessage();

			},
			showSuccessMessage() {
				return new Promise((resolve, reject) => {
					this.$refs.uToast.show({
						title: '资料提交成功',
						type: 'success',
						message: '资料提交成功',
						complete: () => {
							try {
								uni.navigateTo({
									url: "../face/face?mode=create"
								});
								resolve(); // 成功时将Promise标记为已解决
							} catch (error) {
								reject(error); // 如果有错误，将Promise标记为已拒绝
							}
						}
					});
				});
			},
			callAsync(url, method, data) {
				return new Promise((resolve, reject) => {
					this.request(url, method, data, resolve, reject);
				});
			},
			createFormData(idcard, contact, currentImg, drcard) {
				return {
					pid: idcard.pid,
					name: idcard.name,
					gender: idcard.gender,
					birthday: idcard.birthday,
					tel: contact.tel,
					email: contact.email,
					mailAddress: contact.mailAddress,
					contactName: contact.contactName,
					contactTel: contact.contactTel,
					idcardAddress: idcard.address,
					idcardFront: currentImg.idcardFront,
					idcardBack: currentImg.idcardBack,
					idcardHolding: currentImg.idcardHolding,
					idcardExpiration: idcard.expiration,
					drcardType: drcard.carClass,
					drcardExpiration: drcard.validTo,
					drcardIssueDate: drcard.issueDate,
					drcardFront: currentImg.drcardFront,
					drcardBack: currentImg.drcardBack,
					drcardHolding: currentImg.drcardHolding
				};
			},
			checkUploadImages(currentImg) {
				if (Object.keys(currentImg).length !== 6) {
					this.$refs.uToast.show({
						title: '证件上传不完整',
						type: 'error',
						message: '证件上传不完整'
					});
					return false;
				}
				return true;

			},
			confirmSubmission() {
				return new Promise((resolve) => {
					uni.showModal({
						title: '提示信息',
						content: '确认提交实名资料？',
						success: (resp) => {
							resolve(resp.confirm);
						}
					});
				});
			},

			checkValidContactInfo(contact) {
				console.log('validateContactInfo', contact);
				if (this.checkValidTel(contact.tel, '手机号码') &&
					this.checkValidEmail(contact.email, '电子信箱') &&
					this.checkValidAddress(contact.mailAddress, '收信地址') &&
					this.checkValidName(contact.contactName, '联系人') &&
					this.checkValidTel(contact.contactTel, '联系人电话')) {
					console.log('基本信息校验通过');
					return true;

				}
				console.log('基本信息校验失败');
				return false;
			},
		}
	}
</script>

<style lang="less">
	@import url('auth.less');
</style>